from rest_framework import serializers
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import User
from rest_framework.generics import CreateAPIView, RetrieveAPIView
from .serializers import UserCreatSerializer,UserDetailSerializer
from rest_framework.permissions import IsAuthenticated
from rest_framework.generics import UpdateAPIView
from .serializers import EmailSerializer
from rest_framework import status


class UsernameCountView(APIView):
    def get(self,request,username):
        count = User.objects.filter(username=username).count()
        return Response({
            'username':username,
            'count':count,
        })

class MobileCountView(APIView):
    def get(self,request,mobile):
        # 统计手机号是否存在
        count = User.objects.filter(mobile=mobile).count()
        return Response({
            'mobile':'mobile',
            'count':count,
        })

class UserView(CreateAPIView):
    """
    完成用户的注册
    """
    serializer_class = UserCreatSerializer

class UserDetailView(RetrieveAPIView):
    """
    用户详情
    """
    serializer_class = UserDetailSerializer
    #要求登录后才能访问,指定权限认证
    permission_classes = [IsAuthenticated]
    #当前不是根据pk查询对象,而是获取登录的用户对象
    def get_object(self):
        # 当jwt完成登录验证后,会将对象保存到request对象中
        return self.request.user

class EmailView(UpdateAPIView):
    """
    保存用户邮箱
    """
    permission_classes = [IsAuthenticated]
    serializer_class = EmailSerializer

    def get_object(self, *args, **kwargs):
        return self.request.user

class VerifyEmailView(APIView):
    """
    邮箱验证
    """
    def get(self, request):
        # 获取token
        token = request.query_params.get('token')
        if not token:
            return Response({'message': '缺少token'}, status=status.HTTP_400_BAD_REQUEST)

        # 验证token
        user = User.check_verify_email_token(token)
        if user is None:
            return Response({'message': '链接信息无效'}, status=status.HTTP_400_BAD_REQUEST)
        else:
            user.email_active = True
            user.save()
            return Response({'message': 'OK'})


